package com.lk.web.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/** @author likang */
@Controller
public class MainController {

  @GetMapping({"/index", "/", ""})
  public String index(Map<String, Object> map) {
    // 获取用户名的三种方式
    // 第1种方式 SecurityContextHolder,Principal通过源码看就是UserDetails,未认证就是用户名
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal instanceof UserDetails) {
      UserDetails userDetails = (UserDetails) principal;
      String username = userDetails.getUsername();
      map.put("username", username);
    }
    return "index";
  }

  /**
   * 第2种方式
   *
   * @param authentication 认证的用户信息
   */
  @GetMapping("/user/info")
  @ResponseBody
  public Object userInfo(Authentication authentication) {
    return authentication.getPrincipal();
  }

  /**
   * 第3种方式
   *
   * @param userDetails 认证的用户信息
   */
  @GetMapping("/user/info2")
  @ResponseBody
  public Object userInfo2(@AuthenticationPrincipal UserDetails userDetails) {
    return userDetails;
  }
}
